//
//  PushFriendCircleControl.m
//  FreeTime
//
//  Created by  on 16/9/1.
//  Copyright © 2016年 SRDZ.com. All rights reserved.
//

#import "PushFriendCircleControl.h"
#import "Header.h"
#import "XWDragCellCollectionView.h"
#import "QTRejectViewCell.h"
#import "TZImagePickerController.h"

#define PADDING 10

@interface PushFriendCircleControl ()<UICollectionViewDataSource, UICollectionViewDelegate,UICollectionViewDelegateFlowLayout,UIImagePickerControllerDelegate,UINavigationControllerDelegate,XWDragCellCollectionViewDataSource, XWDragCellCollectionViewDelegate,UITextViewDelegate>{
    UITextView * textV;
    UILabel * textViewPlace;
    XWDragCellCollectionView *_collectionView;
    UIView * tableHeaderView,*botmV;
    
    int count;

}

@end

@implementation PushFriendCircleControl

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNav];
    [self setupUI];
}
- (void)setupNav{
    
    UIView * navBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WindowWidth, 64)];
    navBarView.backgroundColor = HOME_COLOR;
    [self.view addSubview:navBarView];
    UIImageView * menuImage = [[UIImageView alloc] initWithFrame:CGRectMake(15, 10, 20, 20)];
    menuImage.image = [UIImage imageNamed:@"login_space"];
    UIButton * leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 20, 70, 40);
//        leftBtn.backgroundColor = [UIColor blueColor];
    [leftBtn addSubview:menuImage];
    [leftBtn addTarget:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];
    [navBarView addSubview:leftBtn];
    UILabel * titleLbl = [ReduceCode creatLabelWithFrame:CGRectMake((WindowWidth-80)/2, 20, 80, 44) title:@"添加标题" titleColor:[UIColor whiteColor] font:17 textAlignment:1];
    [navBarView addSubview:titleLbl];
    
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(WindowWidth-60, 20, 70, 40);
//        rightBtn.backgroundColor = [UIColor blueColor];
    [rightBtn setTitle:@"发送" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightBtn.titleLabel.font = FONT(14);
    [rightBtn addTarget:self action:@selector(saveBtn) forControlEvents:UIControlEventTouchUpInside];
    [navBarView addSubview:rightBtn];
}
- (void)setupUI{
    self.phonelist = [[NSMutableArray alloc]init];
    self.tableView.frame = CGRectMake(0, 64, WindowWidth, WindowHeight-64);
    self.tableView.backgroundColor = RGB_COLOR(239, 239, 244);
    tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WindowWidth, 0)];
    tableHeaderView.backgroundColor = [UIColor whiteColor];
    
    textV = [[UITextView alloc] initWithFrame:CGRectMake(10, 0, WindowWidth-20, 130)];
    textV.backgroundColor = [UIColor whiteColor];
    //    textV.layer.borderColor = [UIColor grayColor].CGColor;
    //    textV.layer.borderWidth = 1;
    textV.delegate = self;
    [tableHeaderView addSubview:textV];
    textViewPlace = [[UILabel alloc] initWithFrame:CGRectMake(5, 4, 190, 20)];
    textViewPlace.font = FONT(14);
    textViewPlace.textColor = [ImageUtil colorWithRgb:0x666666];
    textViewPlace.text = @" 添加标题";
    //    textViewPlace.textAlignment = 0;
    [textV addSubview:textViewPlace];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    _collectionView = [[XWDragCellCollectionView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(textV.frame)+20, WindowWidth,(WindowWidth-50)/4+20) collectionViewLayout:flowLayout];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor whiteColor];
    [_collectionView registerClass:[QTRejectViewCell class] forCellWithReuseIdentifier:@"rejectViewMeCell"];
    [tableHeaderView addSubview:_collectionView];
    //添加照片按钮
    self.btnAddPhone = [UIButton buttonWithType:UIButtonTypeCustom];
    self.btnAddPhone.frame = CGRectMake(10, 10, (WindowWidth-50)/4, (WindowWidth-50)/4);
//    _btnAddPhone.backgroundColor = [UIColor redColor];
    [self.btnAddPhone setBackgroundImage:[UIImage imageNamed:@"pullAdd"] forState:UIControlStateNormal];
    [self.btnAddPhone addTarget:self action:@selector(BtnAddPhoneClick) forControlEvents:UIControlEventTouchUpInside];
    [_collectionView addSubview:self.btnAddPhone];
    
    tableHeaderView.frame = CGRectMake(0, 64, WindowWidth, CGRectGetMaxY(_collectionView.frame));
    self.tableView.tableHeaderView = tableHeaderView;
//    botmV = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_collectionView.frame), WindowWidth, WindowHeight-CGRectGetMaxY(_collectionView.frame))];
//    botmV.backgroundColor = RGB_COLOR(239, 239, 244);
//    self.tableView.tableFooterView = botmV;
    
    
}
#pragma mark - UICollectionViewDataSource

- (NSArray *)dataSourceArrayOfCollectionView:(XWDragCellCollectionView *)collectionView{
    return self.phonelist;
}

- (void)dragCellCollectionView:(XWDragCellCollectionView *)collectionView newDataArrayAfterMove:(NSMutableArray *)newDataArray{
    [self.phonelist removeAllObjects];
    [self.phonelist addObjectsFromArray:newDataArray];
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return self.phonelist.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    QTRejectViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"rejectViewMeCell" forIndexPath:indexPath];
    cell.imageView.image = [self.phonelist objectAtIndex:indexPath.row];
    cell.delBtn.tag = 100+indexPath.row;
    [cell.delBtn addTarget:self action:@selector(BtnDelPhone:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
#pragma mark --UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((WindowWidth-50)/4, (WindowWidth-50)/4);
}

-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(PADDING, PADDING, PADDING, PADDING);
}
-(CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 10;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [self.view endEditing:YES];

}
//删除照片的事件
- (void)BtnDelPhone:(UIButton *)sender{
    [self.phonelist removeObjectAtIndex:sender.tag-100];
    [self resetLayout];
}
//添加图片事件
- (void)BtnAddPhoneClick{
    [self.view endEditing:YES];
    [self showSheetView];
}
//删除照片
- (void)DelClick{
    [self.phonelist removeAllObjects];
    [self resetLayout];
}
-(void)resetLayout{
    int columnCount = ceilf((_phonelist.count + 1) * 1.0 / 4);
    float height = columnCount * ((WindowWidth-50)/4 +10)+10;
    if (height < (WindowWidth-50)/4+20) {
        height = (WindowWidth-50)/4+20;
    }
    if (self.phonelist.count >= 9) {
        self.btnAddPhone.hidden = YES;
    }else{
        self.btnAddPhone.hidden = NO;
        
    }
    CGRect rect = _collectionView.frame;
    rect.size.height = height;
    _collectionView.frame = rect;
    [_collectionView reloadData];
    if (self.btnAddPhone.hidden) {
        return;
    }
    count = 0;
    if (self.phonelist.count < 3) {
        count = 1;
    }else if (self.phonelist.count >=3 ){
        count = 2;
    }
    
    self.btnAddPhone.frame = CGRectMake(10+(10+(WindowWidth-50)/4)*(self.phonelist.count%4), _collectionView.frame.size.height-(WindowWidth-50)/4-10,(WindowWidth-50)/4,(WindowWidth-50)/4);
    tableHeaderView.frame = CGRectMake(0, 64, WindowWidth, CGRectGetMaxY(_collectionView.frame));
//    botmV.frame = CGRectMake(0, CGRectGetMaxY(textV.frame)+10*count+(WindowWidth-40)/3*count, WindowWidth, 120);
//        botmV.frame = CGRectMake(0,CGRectGetMaxY(_collectionView.frame), WindowWidth, WindowHeight-CGRectGetMaxY(_collectionView.frame));
//    scrollView.contentSize = CGSizeMake(WindowWidth,MaxY(botmV)+120);
}
-(void)showSheetView{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *setAlert = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self callCameraOrPhotoWithType:UIImagePickerControllerSourceTypeCamera];
        
    }];
    UIAlertAction *PhoneAlert = [UIAlertAction actionWithTitle:@"从手机选择" style:
                                 UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                     NSInteger Maxcount = 9-self.phonelist.count;
                                     if (Maxcount <= 0) {
                                         return ;
                                     }
                                     TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:Maxcount delegate:nil];
                                     // 你可以通过block或者代理，来得到用户选择的照片.
                                     [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets) {
                                         [self.phonelist addObjectsFromArray:photos];
                                         NSLog(@"phoneList%@",self.phonelist);
                                         [self resetLayout];
                                     }];
                                     // 在这里设置imagePickerVc的外观
                                     imagePickerVc.navigationBar.barTintColor = RGB_COLOR(255, 51, 82);
//                                     imagePickerVc.navigationBar.translucent = NO;
                                     imagePickerVc.oKButtonTitleColorDisabled = [UIColor lightGrayColor];
                                     // imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
                                     // 设置是否可以选择视频/原图
                                     // imagePickerVc.allowPickingVideo = NO;
                                      imagePickerVc.allowPickingOriginalPhoto = NO;
                                     imagePickerVc.modalTransitionStyle = UIModalPresentationFormSheet;
                                     //                                     abcVC.modalTransitionStyle = UIModalPresentationFormSheet;
                                     
                                     [self presentViewController:imagePickerVc animated:YES completion:nil];
                                     
                                 }];
    UIAlertAction *hidAlert = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:setAlert];
    [alert addAction:PhoneAlert];
    [alert addAction:hidAlert];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
    
}
-(void)callCameraOrPhotoWithType:(UIImagePickerControllerSourceType)sourceType{
    BOOL isCamera = YES;
    if (sourceType == UIImagePickerControllerSourceTypeCamera) {//判断是否有相机
        isCamera = [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera];
    }
    if (isCamera) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.delegate = self;
        imagePicker.allowsEditing = NO;//为NO，则不会出现系统的编辑界面
        imagePicker.sourceType = sourceType;
        [self presentViewController:imagePicker animated:YES completion:^(){
            if ([[[UIDevice currentDevice] systemVersion]floatValue]>=7.0) {
                [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
            }
        }];
    } else {
        
    }
}
#pragma UIImagePickerControllerDelegate
//相册或则相机选择上传的实现
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)aImage editingInfo:(NSDictionary *)editingInfo{
    
//    NSArray *photos = [[NSArray alloc]initWithObjects:aImage, nil];
    
    [picker dismissViewControllerAnimated:YES completion:^{
//         [self uploadPhotos:photos];
    }];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString * type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImage * image = info[@"UIImagePickerControllerOriginalImage"];
        image = [ImageUtil reduce:image size:CGSizeMake(270, 254) isAdjust:YES];
        [self.phonelist addObject:image];
//        NSLog(@"phoneList%@",self.phonelist);
        [self resetLayout];
    }
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}
#pragma mark textViewDelegate
- (void)textViewDidChange:(UITextView *)textView;

{
    if ([ToolUtil isBlank:textView.text]) {
        textViewPlace.hidden = NO;
    }else {
        textViewPlace.hidden = YES;
    }
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.view endEditing:YES];
}

#pragma mark -- 响应事件 --
- (void)pop{
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (void)saveBtn{

}
@end
